package myweb.myUdp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.Inet6Address;
import java.net.SocketException;

/**
 * DatagramSocket：通讯的数据管道
 *  --- send和receive
 *  ---(可选，多网卡) 绑定一个IP和Port
 *
 *  DatagramPacket
 *   --集装箱：封装数据
 *   --地址标签：目的地IP+Poer
 *
 * */
public class UDPRecv {
    public static void main(String[] args) {
        try {
            DatagramSocket ds = new DatagramSocket(3000);
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes, 1024);
            System.out.println("udpRev： 我在等消息");
            ds.receive(dp);
            System.out.println("udp: 我在收到消息");
            String strRecv = new String(dp.getData(), 0, dp.getLength())
                    + "from"+dp.getAddress().getHostAddress()+":"+dp.getPort();
            System.out.println(strRecv);
            Thread.sleep(1000);
            System.out.println("Udp: 我要发消息");
            String str = "hello word 222";
            DatagramPacket dp2 = new DatagramPacket(str.getBytes(), str.length(), Inet6Address.getByName("127.0.0.1"), dp.getPort());
            ds.send(dp2);
            System.out.println("UdpRecv : i had send message ");
            ds.close();
        }catch (SocketException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }

}
